package com.jiandian.service.impl;

import com.jiandian.configration.OssConfig;
import com.jiandian.consts.BannerConsts;
import com.jiandian.consts.GameInfoConsts;
import com.jiandian.consts.InitConstant;
import com.jiandian.dao.GameInfoMapper;
import com.jiandian.entity.GameInfo;
import com.jiandian.page.PageInfo;
import com.jiandian.page.WhereMapUtil;
import com.jiandian.service.GameInfoService;
import com.jiandian.service.OssService;
import com.jiandian.util.BeanUtils;
import com.qcloud.cos.model.COSObjectSummary;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.List;

/**
 * 游戏信息
 *
 * @author Houqi Fu
 * @date 2019/01/24
 */
@Service
public class GameInfoServiceImpl implements GameInfoService {

    private static final Logger logger = LoggerFactory.getLogger(GameInfoServiceImpl.class);

    @Autowired
    private GameInfoMapper mapper;

    @Autowired
    private OssService ossService;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public GameInfo add(GameInfo record) {

        int result = mapper.insert(record);
        if (result > 0) {
            return record;
        }
        return null;
    }

    @Override
    public GameInfo update(GameInfo record) {
        Integer id = record.getId();
        if (id == null) {
            return null;
        }
        GameInfo dbGameInfo = mapper.selectByPrimaryKey(id);
        if (dbGameInfo == null) {
            return null;
        }
        BeanUtils.copyProperties(record, dbGameInfo);
        dbGameInfo.setGmtModified(new Timestamp(System.currentTimeMillis()));
        int result = mapper.updateByPrimaryKey(dbGameInfo);
        if (result > 0) {
            return dbGameInfo;
        }
        return null;
    }

    @Override
    public GameInfo findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<GameInfo> findAll(PageInfo pageInfo) {
        return mapper.selectAll(pageInfo);
    }

    @Override
    public int selectCount(PageInfo pageInfo) {
        return mapper.selectCount(pageInfo);
    }

    @Override
    public int batchInsert(List<GameInfo> list) {
        return mapper.batchInsert(list);
    }

    @Override
    public List<GameInfo> batchQueryByIds(List<Integer> ids) {
        return mapper.batchQueryByIds(ids);
    }

    @Override
    public int delete(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delete(GameInfo record) {
        return delete(record.getId());
    }

    @Override
    public int batchDeleteById(List<Integer> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            return mapper.batchDeleteById(ids);
        }
        return 0;
    }

    @Override
    public PageInfo getPage(GameInfo whereEntity, PageInfo pageInfo) {
        pageInfo.setWhereMap(WhereMapUtil.convertBeanToWhereMap(whereEntity));
        pageInfo.setTotalRecord(selectCount(pageInfo));
        pageInfo.queryPageResult(pageInfo);
        pageInfo.setResultObject(findAll(pageInfo));
        return pageInfo;
    }

    @Override
    public GameInfo initBasicValue() {
        GameInfo record = new GameInfo();
        Timestamp now = new Timestamp(System.currentTimeMillis());
        record.setGmtCreate(now);
        record.setGmtModified(now);
        record.setApkAddress(InitConstant.STRING_EMPTY);
        record.setContext(InitConstant.STRING_EMPTY);
        record.setImgs(InitConstant.STRING_EMPTY);
        record.setLogo(InitConstant.STRING_EMPTY);
        record.setName(InitConstant.STRING_EMPTY);
        record.setText(InitConstant.STRING_EMPTY);
        return record;
    }

    @Override
    public GameInfo fetchGameInfoByDirName(String bucketName, String dirName) {

        String realGameName = ossService.getRealGameName(bucketName, dirName);

        String context = ossService.getContext(bucketName, dirName);

        String detailText = ossService.getDetailText(bucketName, dirName);

        GameInfo gameInfo = initBasicValue();
        gameInfo.setName(realGameName);
        gameInfo.setContext(context);
        gameInfo.setText(detailText);
        gameInfo.setFromType(GameInfoConsts.FROM_TYPE_TENCENT);
        String imgsUrl = ossService.getImgsUrl(bucketName, dirName);
        gameInfo.setImgs(imgsUrl);

        gameInfo.setLogo(ossService.getLogoUrl(bucketName, dirName));
        gameInfo.setApkAddress(ossService.getApkUrl(bucketName, dirName));
        return gameInfo;
    }

    @Transactional
    @Override
    public boolean syncAll(String bucketName) {
        // 先查询此刻最大id
        int maxId = 0;
       try {
           maxId = mapper.selectMaxId();
       }catch (Exception e){

       }
        List<COSObjectSummary> cosObjectSummaries = ossService.listDir(bucketName, "", false);
        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
            String dirName = "";
            // 如果是目录
            String key = cosObjectSummary.getKey();

            // 是否游戏标示
            boolean ifGame = true;
            if (cosObjectSummary.getSize() != 0L) {
                ifGame = false;
            }
            if (StringUtils.contains(key, "img")) {
                ifGame = false;

            }
            // 解码为中文
            try {
                key = StringUtils.replace(key, "/", "");
                dirName = URLDecoder.decode(key, "UTF-8");
            } catch (Exception e) {
                continue;
            }

            if (StringUtils.contains(dirName, BannerConsts.BANNER_DIR_NAME) || StringUtils.contains(dirName, BannerConsts.APK_DIR_NAME)) {
                ifGame = false;
            }

            if (ifGame) {
                GameInfo gameInfo = fetchGameInfoByDirName(ossConfig.getBucketName(), dirName);
                add(gameInfo);
            }
        }
        // 删除之前的需要刷新的游戏信息
        deleteRefreshScopeByMaxId(maxId, GameInfoConsts.FROM_TYPE_TENCENT);
        return true;

    }

    @Override
    public int deleteByMaxId(Integer id) {
        return mapper.deleteByMaxId(id);
    }

    public void deleteRefreshScopeByMaxId(int maxId,String fromType){
        mapper.deleteRefreshScopeByMaxId(maxId,fromType);
    }
}
